package net.sf.sbv.modals;


import java.util.ArrayList;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Pratik
 */
public class Contact {
    private static int MIN_EQUAL_DIGITS = 10;

    private String name;
    private String phoneNumber;
    ArrayList<Message> messageList;

    public Contact(String inputName, String inputNumber) {
        name = inputName;
        phoneNumber = inputNumber;
        messageList = new ArrayList<Message>();
    }

    public String getName() {
        return name;
    }

    public String getNumber() {
        return phoneNumber;
    }

    public ArrayList<Message> getMessages() {
        return messageList;
    }

    public void addMessage(Message msgToAdd) {
        msgToAdd.setContact(this);
        messageList.add(msgToAdd);
    }

    @Override
    public String toString() {
        return name + ", " + phoneNumber;
    }

    @Override
    public boolean equals(Object obj) {
        if(obj == null || !(obj instanceof Contact)) {
            return false;
        }

        Contact con = (Contact)obj;
        //check if the phone number is exactly equal
        boolean equal = phoneNumber.equals(con.phoneNumber);

        if(!equal) {
            //check if the MIN_EQUAL_DIGITS digits are equal from Right side
            if(con.phoneNumber.length() >= MIN_EQUAL_DIGITS) {
                equal = phoneNumber.contains(getActualNumber(con.phoneNumber));
            }
        }

        return equal;
    }

    @Override
    public int hashCode() {
        int hash = 5;
        
        String newPhoneNumberForHashCode = getActualNumber(this.phoneNumber);
        if(newPhoneNumberForHashCode == null) {
            newPhoneNumberForHashCode = "";
        }

        hash = 11 * hash + newPhoneNumberForHashCode.hashCode();
        return hash;
    }

    private static String getActualNumber(String number) {
        if(number == null) {
            return null;
        }
        
        int len = number.length();
        if(len >= MIN_EQUAL_DIGITS) {
            number = number.substring(len - MIN_EQUAL_DIGITS);
        }

        return number;
    }
}
